package com.czk.zookeeper.curator.lock;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/7 22:36
 */
public class CuratorLockTest {
    String IP = "192.168.25.133:2181,192.168.25.133:2182,192.168.25.133:2183";
    CuratorFramework client;

    @Before
    public void before() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.builder()
                .connectString(IP)
                .sessionTimeoutMs(50000)
                .retryPolicy(retryPolicy)
                .build();
        client.start();
    }

    @After
    public void after() {
        client.close();
    }

    /**
     * 排它锁
     * @throws Exception
     */
    @Test
    public void test1() throws Exception{
        // 1 连接对象
        // 2 节点路径
        InterProcessLock interProcessLock=new InterProcessMutex(client,"/lock1");
        System.out.println("等待去获取锁");
        interProcessLock.acquire();
        for (int i = 0; i < 10; i++) {
            TimeUnit.SECONDS.sleep(5);
            System.out.println(i);
        }
        // 释放锁
        interProcessLock.release();
        System.out.println("等待释放锁");
    }

    /**
     * 读写锁
     * @throws Exception
     */
    @Test
    public void test2() throws Exception{
        InterProcessReadWriteLock interProcessReadWriteLock=new InterProcessReadWriteLock(client,"/lock1");
        // 读锁对象
        InterProcessMutex interProcessMutex = interProcessReadWriteLock.readLock();
        // 获取写锁对象
        InterProcessMutex interProcessMutex1 = interProcessReadWriteLock.readLock();
        // 写作获取
        interProcessMutex.acquire();
        System.out.println("等待获取读锁对象");
        for (int i = 0; i < 10; i++) {
            TimeUnit.SECONDS.sleep(5);
            System.out.println(i);
        }
        // 释放锁
        interProcessMutex.release();
        System.out.println("释放锁了");
    }

}
